package com.acorn.community.common.annotation.access;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.Objects;

/**
 * 方法参数拦截器
 *
 * @author tianshiwei
 */
@Slf4j
@Component
public class AccessUserProcessor implements HandlerMethodArgumentResolver {

    public final static String X_GLOBAL_USER_TOKEN = "token";

    public final static String USER_ID = "userId";
    public final static String OPEN_ID = "openid";

//    @Resource
//    private RedisDataHandler redisDataHandler;
//    @Resource
//    private TokenHandler tokenHandler;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(AccessUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Class clazz = methodParameter.getParameterType();
        Object obj = clazz.newInstance();

//        //进行赋值
//        String token = nativeWebRequest.getHeader(X_GLOBAL_USER_TOKEN);
//
//        log.info("AccessUserProcessor supportsParameter id:{}", token);
//
//        if (Objects.isNull(token)) {
//            return obj;
//        }
//
//        UserEntity userEntity = redisDataHandler.getUserEntity(tokenHandler.getOpenid(token));
//        if (Objects.isNull(userEntity)) {
//            return obj;
//        }
//
//
//        //设置userId
//        setField(clazz, obj, userEntity.getId(), USER_ID);
//        //设置openId
//        setField(clazz, obj, userEntity.getOpenid(), OPEN_ID);

        return obj;
    }

    public void setField(Class clazz, Object obj, Object value, String fieldName) {
//        try {
//            Field declaredField = clazz.getDeclaredField(fieldName);
//            if (Objects.nonNull(declaredField)) {
//                declaredField.setAccessible(true);
//                declaredField.set(obj, StringUtils.equals(fieldName, USER_ID) ? Long.parseLong(value.toString()) : URLDecoder.decode(value.toString(), "utf-8"));
//            }
//        } catch (Exception e) {
//            log.error("resolveArgument setField error:{}", e.getMessage());
//            throw new BusinessException(-1, "access user fail");
//        }
    }


}
